<template>
  <div class="box">
    <div id="cesiumContainer"></div>
    <!-- <div class="yy">
      <label>当前水位: <span id="currentLevel">50</span> 米</label>
    </div> -->
    <div class="button">
      <input
        type="range"
        id="waterLevel"
        min="0"
        max="100"
        value="50"
        step="1"
      />
      <span id="currentLevel">50</span>米
      <button onclick="toggleAnimation()">波浪动画</button>
    </div>
  </div>
</template>

<script>
import Line from "./line.json";
export default {
  data() {
    return {
      value: "",
      activeShapePoints: "",
      floatingPoint: "",
      activeShape: "",
      handler: "",
      maxWaterHeight: "",
      minWaterHeight: "",
      waterHeight: "",
      tempEntities: "",
      undefinedisDraw: "",
      isDraw: false,
      polylinedata: "",
      viewer: null,
      entity: null,
      startMousePosition: null,
      currentMousePosition: null,
      position: {
        longitude: 116.39,
        latitude: 39.9,
        height: 0,
      },
      orientation: {
        heading: 0,
        pitch: 0,
        roll: 0,
      },

      //   isDraw: false,
      //  maxWaterHeight: 2000,
      minWaterHeight: 0,
      warningWaterHeight: 0, // 预警高度
      waterHeight: 0,
      waterHeightShow: false,
      speed: "1",
      waterHeightTimeer: 0,
      waterPrimitive: undefined,
      // tempEntities: [],
      viewModel: {
        emissionRate: 1,
        gravity: 0.0, //设置重力参数
        minimumParticleLife: 1,
        maximumParticleLife: 2,
        minimumSpeed: 0.00002, //粒子发射的最小速度
        maximumSpeed: 0.00006, //粒子发射的最大速度
        speed: 0.3,
        startScale: 30,
        endScale: 50,
        particleSize: 2,
      },
      emitterModelMatrix: null,
      translation: null,
      rotation: null,
      hpr: null,
      trs: null,
      scene: null,
      particleSystem: "",
    };
  },
  mounted() {
    this.initview();
  },
  methods: {
    initview() {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJjMzU2ZTQyYy1iOTU5LTQ5MDQtOGNkNC0yYzcxMTI1ZDJiZGQiLCJpZCI6NzY1OTcsImlhdCI6MTYzOTU2MDcwOH0.kbWigipGD6l2OPBGpnkkN6dzp8NuNjoHNNM1NF4gaIo";
      const viewer = new Cesium.Viewer("cesiumContainer", {
        // terrainProvider: Cesium.createWorldTerrain({
        //   url: "https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles",
        //   requestVertexNormals: true,
        //   requestWaterMask: true, // 展示地形和水体遮罩
        // }),
        requestRenderMode: true, // 按需渲染
        scene3DOnly: true, // 纯3D模式
        shadows: false, // 关闭阴影
        fxaa: false, // 关闭抗锯齿
        shouldAnimate: true, // 关闭自动动画
        msaaSamples: 4, // 中端设备用4x
        useBrowserRecommendedResolution: false, // 禁用自动分辨率
        targetFrameRate: 60, // 目标帧率
      });
      // 使用低分辨率或简化版底图
      viewer.imageryProvider = new Cesium.ArcGisMapServerImageryProvider({
        url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer",
      });
      // 使用简化地形或关闭地形
      viewer.terrainProvider = Cesium.createWorldTerrain({
        requestWaterMask: false, // 关闭水面效果
        requestVertexNormals: false, // 关闭顶点法线
      });
      // 减少最大可视距离
      viewer.scene.screenSpaceCameraController.maximumZoomDistance = 10000000;
      // 降低地形细节
      viewer.scene.terrainExaggeration = 1.0;
      // 启用预加载
      viewer.scene.preloadFlightDestinations = true;
      viewer.scene.preloadAnimatedCameraPosition = true;
      // 只加载可视范围内的数据
      viewer.scene.globe.tileCacheSize = 1000;
      viewer.scene.fog.enabled = false;
      this.viewer = viewer;
      // 去除logo
      viewer.cesiumWidget.creditContainer.style.display = "none";
      // 显示帧率
      viewer.scene.debugShowFramesPerSecond = true;
      viewer.scene.globe.depthTestAgainstTerrain = true;
      // 调试使用
      window.viewer = viewer;

      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          112.7460645937131,
          31.135216886898544,
          500
          // 116.391,
          // 39.907,
          // 50
        ),
        // orientation: {
        //   heading: Cesium.Math.toRadians(0),
        //   pitch: Cesium.Math.toRadians(-30),
        // },
      });

      // 水库位置参数
      const reservoirPosition = Cesium.Cartesian3.fromDegrees(
        112.7460645937131,
        31.135216886898544,
        500
      );
      const reservoirRadius = 800;

      // 自定义着色器材质
      const waterMaterial = new Cesium.Material({
        fabric: {
          type: "WaterSurface",
          uniforms: {
            waterLevel: 50.0,
            time: 0.0,
            waveSpeed: 0.5,
            shallowColor: new Cesium.Color(0.1, 0.5, 0.8, 0.6),
            deepColor: new Cesium.Color(0.0, 0.2, 0.6, 0.8),
          },
          source: `
        czm_material czm_getMaterial(czm_materialInput materialInput)
        {
            czm_material material = czm_getDefaultMaterial(materialInput);
            
            // 水位高度计算
            float baseHeight = u_waterLevel;
            float waveHeight = sin(materialInput.position.x * 0.01 + u_time * u_waveSpeed) * 
                             cos(materialInput.position.z * 0.01 + u_time * u_waveSpeed) * 2.0;
            
            // 垂直偏移
            float verticalOffset = baseHeight + waveHeight;
            
            // 颜色渐变
            float depthFactor = clamp((verticalOffset - materialInput.position.y) / 20.0, 0.0, 1.0);
            vec4 finalColor = mix(u_shallowColor, u_deepColor, depthFactor);
            
            // 镜面高光
            vec3 viewDir = normalize(materialInput.positionToEyeEC);
            vec3 normal = vec3(0.0, 1.0, 0.0);
            float specular = pow(max(dot(viewDir, normal), 0.0), 32.0);
            
            material.diffuse = finalColor.rgb;
            material.alpha = finalColor.a;
            material.specular = specular * 0.5;
            
            return material;
        }
        `,
        },
      });

      // 创建水面实体
      const waterEntity = viewer.entities.add({
        position: reservoirPosition,
        ellipse: {
          semiMinorAxis: reservoirRadius,
          semiMajorAxis: reservoirRadius,
          height: 50,
          material: waterMaterial,
          extrudedHeight: 50,
        },
      });

      // 动画控制变量
      let isAnimating = false;
      let lastTime = Date.now();

      // 更新材质统一变量
      function updateMaterial() {
        const now = Date.now();
        const deltaTime = (now - lastTime) / 1000;
        lastTime = now;

        if (isAnimating) {
          waterMaterial.uniforms.time += deltaTime;
        }

        waterMaterial.uniforms.waterLevel = parseFloat(
          document.getElementById("waterLevel").value
        );

        waterEntity.ellipse.height = waterMaterial.uniforms.waterLevel;
        waterEntity.ellipse.extrudedHeight = waterMaterial.uniforms.waterLevel;
        document.getElementById("currentLevel").textContent = Math.round(
          waterMaterial.uniforms.waterLevel
        );
      }

      // 绑定控件事件
      document
        .getElementById("waterLevel")
        .addEventListener("input", updateMaterial);
      window.toggleAnimation = () => {
        isAnimating = !isAnimating;
        if (isAnimating) lastTime = Date.now();
      };

      // 设置相机初始视角
      // viewer.camera.flyTo({
      //   destination: Cesium.Cartesian3.fromDegrees(116.391, 39.91, 2000),
      //   orientation: {
      //     heading: Cesium.Math.toRadians(0),
      //     pitch: Cesium.Math.toRadians(-30),
      //     roll: 0.0,
      //   },
      // });

      // 注册每帧更新
      viewer.scene.postUpdate.addEventListener(updateMaterial);
    },
  },
};
</script>

<style lang="scss" scoped>
#cesiumContainer {
  position: absolute;
  width: 100%;
  height: 100vh;
  top: 0px;
  left: 0px;
  overflow: hidden;
}
.button {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1;
}
.box {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
.yy {
  position: absolute;
  top: 50px;
  left: 10px;
  z-index: 1;
}
</style>